#define _CRT_SECURE_NO_WARNINGS
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,
        int inBegin, int inEnd,
        int poBegin, int poEnd
    )
    {
        if (inBegin > inEnd) return nullptr;
        int k = postorder[poEnd];
        TreeNode* root = new TreeNode(k);
        for (int i = 0; i < inorder.size(); i++)
        {
            //[inBegin, i-1] i [i+1, inEnd]
            //[poBegin, poBegin+i-1-inBegin] [poBegin+i-1-inBegin+1, poEnd-1] poEnd
            if (k == inorder[i])
            {
                root->left = _buildTree(inorder, postorder, inBegin, i - 1,
                    poBegin, poBegin + i - 1 - inBegin);
                root->right = _buildTree(inorder, postorder, i + 1, inEnd,
                    poBegin + i - 1 - inBegin + 1, poEnd - 1);
                break;
            }
        }
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return _buildTree(inorder, postorder,
            0, inorder.size() - 1, 0, postorder.size() - 1);
    }
};
